import fetch from 'isomorphic-fetch'


export const REQUEST_POSTS = 'REQUEST_POSTS'
export const RECEIVE_POSTS = 'RECEIVE_POSTS'
export const RECEIVE_SAVE = 'RECEIVE_SAVE'
export const RECEIVE_REMOVE = 'RECEIVE_REMOVE'

//开始获取数据
const requestPosts = path => {
  return {
    type: REQUEST_POSTS,
    path
  }
}

//获取数据成功
const receivePosts = (path, json) => {
  return {
        type: RECEIVE_POSTS,
        path ,
        json 
    }
}

//获取数据成功
const receiveSave = (path, json) => {
  return {
        type: RECEIVE_SAVE,
        path ,
        json 
    }
}

//获取数据成功
const receiveRemove = (path, json) => {
  return {
        type: RECEIVE_REMOVE,
        path ,
        json 
    }
}

// 页面初次渲染时获取数据
export const fetchPosts = (path, postData) => {
    return dispatch => {
        dispatch(requestPosts(path));
        return fetch(path,{
            method:"post",
            mode: 'cors',
            body: JSON.stringify(postData),
            headers: {
                'Content-type': "application/json;charset=utf-8"
            }            
        }).then(response => {
            if (response.ok) {
                response.json().then(json => dispatch(receivePosts(path, json)))
            } else {
                console.log("status", response.status);
            }
        })
        .catch(error => console.log(error))
    }
}

// 页面初次渲染时获取数据
export const saveRecord = (path, postData) => {
    return dispatch => {
        dispatch(requestPosts(path));
        return fetch(path,{
            method:"post",
            mode: 'cors',
            body: JSON.stringify(postData),
            headers: {
                'Content-type': "application/json;charset=utf-8"
            }            
        }).then(response => {
            if (response.ok) {
                response.json().then(json => dispatch(receiveSave(path, json)))
            } else {
                console.log("status", response.status);
            }
        })
        .catch(error => console.log(error))
    }
}




// 删除记录
export const delRecord = (path) => {
    return dispatch => {
        dispatch(requestPosts(path));
        return fetch(path,{
            method:"get",
            mode: 'cors',
            headers: {
                'Content-type': "application/json;charset=utf-8"
            }            
        }).then(response => {
            if (response.ok) {
                response.json().then(json => dispatch(receiveRemove(path, json)))
            } else {
                console.log("status", response.status);
            }
        })
        .catch(error => console.log(error))
    }
}

